package cn.iocoder.yudao.module.lowcode.controller.admin.script;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.lowcode.core.cache.GroovyScriptCacheManagerSafe;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * Groovy脚本健康检查 Controller
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - Groovy脚本健康检查")
@RestController
@RequestMapping("/lowcode/groovy-script-health")
@Slf4j
public class GroovyScriptHealthController {

    @Resource
    private GroovyScriptCacheManagerSafe groovyScriptCacheManagerSafe;

    @GetMapping("/status")
    @Operation(summary = "获取Groovy脚本模块状态")
    @PreAuthorize("@ss.hasPermission('lowcode:groovy-script:query')")
    public CommonResult<Map<String, Object>> getStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 获取预加载状态
            GroovyScriptCacheManagerSafe.PreloadStatus preloadStatus = 
                groovyScriptCacheManagerSafe.getPreloadStatus();
            
            status.put("moduleEnabled", true);
            status.put("preloadCompleted", preloadStatus.isCompleted());
            status.put("preloadSuccessCount", preloadStatus.getSuccessCount());
            status.put("preloadErrorCount", preloadStatus.getErrorCount());
            status.put("errorScripts", preloadStatus.getErrorScripts());
            
            // 健康状态判断
            boolean healthy = preloadStatus.isCompleted() && 
                             (preloadStatus.getErrorCount() == 0 || 
                              preloadStatus.getSuccessCount() > 0);
            status.put("healthy", healthy);
            
            if (!healthy) {
                status.put("healthMessage", "存在脚本编译错误或预加载未完成");
            } else {
                status.put("healthMessage", "模块运行正常");
            }
            
        } catch (Exception e) {
            log.error("获取Groovy脚本模块状态失败", e);
            status.put("moduleEnabled", false);
            status.put("healthy", false);
            status.put("healthMessage", "模块异常: " + e.getMessage());
        }
        
        return success(status);
    }

    @PostMapping("/clear-cache")
    @Operation(summary = "清除脚本缓存")
    @PreAuthorize("@ss.hasPermission('lowcode:groovy-script:update')")
    public CommonResult<Boolean> clearCache(@RequestParam(required = false) String scriptName) {
        try {
            if (scriptName != null && !scriptName.trim().isEmpty()) {
                groovyScriptCacheManagerSafe.evictScript(scriptName.trim());
                log.info("清除脚本缓存成功: {}", scriptName);
            } else {
                groovyScriptCacheManagerSafe.evictAll();
                log.info("清除所有脚本缓存成功");
            }
            return success(true);
        } catch (Exception e) {
            log.error("清除脚本缓存失败", e);
            return CommonResult.error(500, "清除缓存失败: " + e.getMessage());
        }
    }

    @PostMapping("/reload-scripts")
    @Operation(summary = "重新加载脚本")
    @PreAuthorize("@ss.hasPermission('lowcode:groovy-script:update')")
    public CommonResult<Map<String, Object>> reloadScripts() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 清除所有缓存
            groovyScriptCacheManagerSafe.evictAll();
            
            // 触发重新预加载 - 这里可以添加手动预加载的方法
            // 暂时返回操作结果
            result.put("success", true);
            result.put("message", "缓存已清除，脚本将在下次调用时重新加载");
            
            log.info("手动重新加载脚本操作完成");
            return success(result);
            
        } catch (Exception e) {
            log.error("重新加载脚本失败", e);
            result.put("success", false);
            result.put("message", "重新加载失败: " + e.getMessage());
            return success(result);
        }
    }

    @GetMapping("/test-script/{scriptName}")
    @Operation(summary = "测试脚本编译")
    @PreAuthorize("@ss.hasPermission('lowcode:groovy-script:query')")
    public CommonResult<Map<String, Object>> testScript(@PathVariable String scriptName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 尝试获取脚本实例来测试编译
            groovyScriptCacheManagerSafe.getScriptInstance(scriptName);
            
            result.put("success", true);
            result.put("message", "脚本编译测试成功");
            result.put("scriptName", scriptName);
            
            return success(result);
            
        } catch (Exception e) {
            log.warn("脚本编译测试失败: {}", scriptName, e);
            
            result.put("success", false);
            result.put("message", "脚本编译失败: " + e.getMessage());
            result.put("scriptName", scriptName);
            result.put("error", e.getClass().getSimpleName());
            
            return success(result);
        }
    }
}